<template>
  <div>
    <div class="app-container">
      <!--工具栏-->
      <div class="head-container">
        <div v-if="crud.props.searchToggle">
          <el-input v-model="query.taskName" size="small" clearable class="filter-item" style="width: 200px" placeholder="请输入任务名称" @keyup.enter.native="crud.toQuery" />

          <el-select v-model="query.contrastTemplatePkId" class="filter-item" style="width: 200px" placeholder="请选择模板名称" filterable clearable>
            <el-option
              v-for="item in contrastTemplateList"
              :key="item.pkId"
              :label="item.name"
              :value="item.pkId"
              size="small"
              clearable
            />
          </el-select>
          <el-select v-model="query.serverPkId" class="filter-item" style="width: 200px" placeholder="请选择服务器" filterable clearable>
            <el-option
              v-for="item in sourceDataSourceList"
              :key="item.pkId"
              :label="item.sourceName"
              :value="item.pkId"
              size="small"
              clearable
            />
          </el-select>
          <el-select v-model="query.status" class="filter-item" placeholder="请选择比对状态" filterable clearable style="width:200px">
            <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
          <el-date-picker
            v-model="query.crtTs"
            class="date-item"
            style="margin-right: 3px;"
            type="daterange"
            range-separator=":"
            size="small"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            clearable
          />
          <rrOperation :crud="crud" />
        </div>
        <crudOperation show="" :permission="permission" />
      </div>
      <el-table
        ref="table"
        :data="crud.data"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column v-if="columns.visible('taskName')" :show-overflow-tooltip="true" prop="taskName" label="任务名称" min-width="170" />
        <el-table-column v-if="columns.visible('contrastTemplatePkId')" :show-overflow-tooltip="true" prop="contrastTemplatePkId" label="模板名称" min-width="110">
          <template slot-scope="scope">
            {{ getContrastTemplateName(scope.row.contrastTemplatePkId) }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('migrationType')" :show-overflow-tooltip="true" prop="migrationType" label="迁移类型" min-width="150" />
        <el-table-column v-if="columns.visible('serverPkId')" prop="serverPkId" label="数据服务器" min-width="150">
          <template slot-scope="scope">
            {{ getServerName(scope.row.serverPkId) }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('status')" label="比对状态" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 'TODO'" type="info">待比对</el-tag>
            <el-tag v-if="scope.row.status === 'PROCESSING'">比对中</el-tag>
            <el-tag v-if="scope.row.status === 'FINISH'" type="success">完成</el-tag>
            <el-tag v-if="scope.row.status === 'FAIL'" type="danger">失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('total')" prop="total" label="比对进度" min-width="280">
          <template slot-scope="scope">
            <el-tag type="info">总数: {{ scope.row.total }}</el-tag>
            <el-tag type="success" style="margin: 0px 5px">比对成功: {{ scope.row.successCount }}</el-tag>
            <el-tag type="danger">比对失败: {{ scope.row.failCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('startTime')" prop="startTime" label="开始时间" min-width="150">
          <template slot-scope="scope">
            <div>
              <i class="el-icon-time" />
              <span style="margin-left: 5px">{{ scope.row.startTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('endTime')" prop="endTime" label="结束时间" min-width="150">
          <template slot-scope="scope">
            <div>
              <i class="el-icon-time" />
              <span style="margin-left: 5px">{{ scope.row.endTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('upUserName')" prop="upUserName" label="更新人" />
        <el-table-column v-if="columns.visible('upTs')" prop="upTs" label="更新时间" min-width="150" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="text" icon="el-icon-view" @click="toDetail(scope.row)">任务详情</el-button> -->
            <el-button
              size="mini"
              style="margin-left: 10px !important;"
              type="text"
              @click="toContrastRunLog(scope.row)"
            >对比记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination />
      <!--新增/编辑任务弹窗-->
      <el-dialog
        v-if="crud.status.cu > 0 || detailsFlag === true"
        append-to-body
        :close-on-click-modal="false"
        :modal="false"
        :before-close="cancelCU"
        :visible.sync="crud.status.cu > 0 || detailsFlag === true"
        :title="crud.status.title"
        width="1200px"
        top="2vh"
      >
        <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="130px">
          <data-contrast-list :dialog-type="dialogType" :form="form" :task-pk-id="form.pkId" />
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button @click="cancelAndClose">取消</el-button>
          <el-button v-if="detailsFlag === false" type="primary" @click="saveAddOrEdit">确定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        v-if="contrastLogFlag"
        append-to-body
        :close-on-click-modal="false"
        :before-close="cancelCU"
        :visible.sync="contrastLogFlag"
        :title="`${taskName} 跨库比对记录`"
        width="1200px"
        top="5vh"
      >
        <contrast-run-log ref="logPage" :run-log-data="runLogData" :task-pk-id="taskPkId" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import dataSourceApi from '@/api/metadata/dataSource'
import contrastTaskApi from '@/api/data/contrast/contrastTask'
import contrastTemplateApi from '@/api/data/contrast/contrastTemplate'
import contrastListApi from '@/api/data/contrast/contrastList'
import validateTaskName from '@/utils/taskNameRepeat'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/expand/data/contrast/task/CRUD.operation.vue'
import pagination from '@crud/Pagination'
import DataContrastList from './data-contrast-list'
import ContrastRunLog from './contrast-run-log'

const defaultCrud = CRUD({
  title: '数据对比',
  url: 'api/cross/db/contrast/task',
  crudMethod: { ...contrastTaskApi }
})
const defaultForm = {
  pkId: '',
  contrastFailCount: '',
  contrastSuccessCount: '',
  contrastTemplateName: '',
  contrastTotal: '',
  crtTs: '',
  crtUser: '',
  crtUserName: '',
  remark: '',
  sourceConnName: '',
  serverPkId: '',
  contrastTemplatePkId: '',
  sourceServer: '',
  status: 'TODO',
  taskCode: '',
  taskName: '',
  upTs: '',
  upUser: '',
  upUserName: '',
  contrastTemplatePkIds: [],
  dataContrastList: [],
  dataTableList: [],
  sourceDbName: ''
}

export default {
  components: { ContrastRunLog, DataContrastList, crudOperation, rrOperation, pagination },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      permission: {
        add: ['admin', 'contrast:add'],
        edit: ['admin', 'contrast:edit'],
        del: ['admin', 'contrast:del']
      },
      statusOptions: [
        { key: 'TODO', label: '待比对' },
        { key: 'PROCESSING', label: '比对中' },
        { key: 'FINISH', label: '完成' },
        { key: 'FAIL', label: '失败' }
      ],
      tableHeight: window.innerHeight - 248, // 表格动态高度
      screenHeight: window.innerHeight, // 内容区域高度
      detailFlag: false,
      fieldFlag: false,
      fields: '',
      sqlFlag: false,
      fileList: [],
      modelFlag: false,
      detailsFlag: false,
      contrastLogFlag: false,
      contrastList: {},
      runLogData: {},
      taskName: '',
      taskPkId: '',
      sourceDataSourceList: [],
      contrastTemplateList: [],
      dataStatusDict: [],
      dataStatusFilters: [],
      dialogType: null,
      rules: {
        taskName: [
          { required: true, validator: validateTaskName.bind(this, contrastTaskApi, this.form), trigger: 'blur' }
        ],
        contrastTemplatePkIds: [
          { required: true, message: '请选择比对模板', trigger: 'blur' }
        ],
        serverPkId: [
          { required: true, message: '请选择数据服务器', trigger: 'blur' }
        ],
        sourceDbName: [
          { required: true, message: '请选择库名', trigger: 'blur' }
        ]
      }
    }
  },
  // 动态控制列表table数据内容高度
  watch: {
    // 监听screenHeight从而改变table的高度
    screenHeight(val) {
      this.screenHeight = val
      this.tableHeight = this.screenHeight - 248
    }
  },
  mounted() {
    // window.onresize:浏览器尺寸变化响应事件
    window.onresize = () => {
      return (() => {
        // window.innerHeight:浏览器的可用高度
        window.screenHeight = window.innerHeight
        this.screenHeight = window.screenHeight
      })()
    }
  },
  created() {
    this.initData()
    this.crud.resetQuery(false)
  },
  methods: {
    [CRUD.HOOK.beforeToAdd](crud) {
      this.form = crud.form
      this.dialogType = 1
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.form = crud.form
      this.dialogType = 2
      this.taskPkId = form.pkId
      // 用于编辑功能时获取任务名称
      this.form.validateName = this.form.taskName
      const param = {
        'taskPkId': form.pkId
      }
      contrastListApi.findListByPage(param).then(data => {
        this.form.dataContrastList = data.content
      })
    },
    // 初始化数据
    initData() {
      this.getDataSource()
      this.getContrastTemplate()
    },
    getDataSource() {
      const param = { sourceAttribute: 'source', size: 500 }
      dataSourceApi.findListByPage(param).then(data => {
        this.sourceDataSourceList = data.content
      })
    },
    getContrastTemplate() {
      const param = { sourceAttribute: 'source', size: 500 }
      contrastTemplateApi.findListByPage(param).then(data => {
        this.contrastTemplateList = data.content
      })
    },
    cancelAndClose() {
      if (this.crud.status.cu !== 0) {
        this.crud.cancelCU()
      } else {
        this.detailsFlag = false
      }
      this.crud.refresh()
    },
    saveAddOrEdit() {
      if (this.form.taskName === undefined || this.form.taskName === '' || this.form.taskName === null) {
        this.crud.notify('请先填写任务名称！', CRUD.NOTIFICATION_TYPE.WARNING)
      } else if (this.form.contrastTemplatePkId === undefined || this.form.contrastTemplatePkId === '' || this.form.contrastTemplatePkId === null) {
        this.crud.notify('请先选择模板！', CRUD.NOTIFICATION_TYPE.WARNING)
      } else if (this.form.serverPkId === undefined || this.form.serverPkId === '' || this.form.serverPkId === null) {
        this.crud.notify('请先选择源数据源类型！', CRUD.NOTIFICATION_TYPE.WARNING)
      } else if (this.form.dataContrastList.length <= 0) {
        this.crud.notify('请先选择需要比对的表！', CRUD.NOTIFICATION_TYPE.WARNING)
      } else {
        contrastTaskApi.edit(this.form).then(rsp => {
          this.crud.notify(rsp, CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.refresh()
          this.cancelCU()
        })
      }
    },
    cancelCU() {
      this.crud.cancelCU()
      this.detailsFlag = false
      this.contrastLogFlag = false
    },
    // 查看任务详情
    // toDetail(row) {
    //   this.form = row
    //   const param = { taskPkId: row.pkId }
    //   contrastListApi.findListByPage(param).then(data => {
    //     this.form.dataContrastList = data.content
    //   })
    //   this.dialogType = 0
    //   this.detailsFlag = true
    // },
    // 查看对比记录
    toContrastRunLog(row) {
      this.taskName = row.taskName
      this.taskPkId = row.pkId
      this.contrastLogFlag = true
    },
    getContrastTemplateName(val) {
      const template = this.contrastTemplateList.find(temp => val === temp.pkId)
      return (template ? template.name : '无')
    },
    getServerName(val) {
      const server = this.sourceDataSourceList.find(temp => val === temp.pkId)
      return (server ? server.sourceName : '无')
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container .el-divider--horizontal {
  margin: 5px 0px;
}
</style>
